<template>
	<view class="container">
		<view class="titles">
			蓝牙列表
		</view>
		<scroll-view>
			<view>
				<view v-for="(item, index) in devicesList" :key="index" @click.native="connect(item)"
					class="cu-item">
					<view class="item-left">
						<view class="names">{{item.name}}</view>
						<view class="service">{{item.advertisServiceUUIDs&& item.advertisServiceUUIDs.length || 0}}
							Service Advertised</view>
						<view class="device">
							{{item.deviceId}}
						</view>
					</view>
					<view class="item-right">
						<view class="dbm">{{item.RSSI}}dBm</view>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		name: "ble-list",
		data() {
			return {
				devicesList: [
					// 测试数据
					// {
					// 	name: "12222tetrytytuyiuikuoioip99999994243546546567768787989809",
					// 	deviceId: "99999994243546546567768787989809---8787989809",
					// 	RSSI: "-90"
					// },
				]
			};
		},
		watch: {
			// 监听蓝牙设备
			'$store.state.devicesList': {
				immediate: true,
				deep: true,
				handler(e) {
					console.log(e)
					if (e.length > 0) {
						this.devicesList = e
					}
				}
			},
		},
		created() {

		},
		onLoad() {
			this.$store.dispatch('startBluetoothDevicesDiscovery')
				.then(res => {
					console.log(res)
				})
				.catch(err => {
					console.log(err)
				})
		},
		methods: {
			// 连接设备
			async connect(item) {
				uni.navigateTo({
					url:"/pages/index/index"
				})
				try {
					await this.$store.dispatch('createBLEConnection', item)
				} catch (err) {}
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/css/common.scss";

	.container {
		padding: 60rpx 40rpx;

		.titles {
			font-size: 40rpx;
			color: #000000;
			font-weight: bold;
			margin-bottom: 50rpx;
		}

		/deep/ .u-list-item {
			@include flexLayout(center, space-between);
			flex-direction: row;
			border-bottom: 2rpx solid #efefef;
			padding: 20rpx 0;

			.item-left {
				width: 85%;
				word-break: break-all;

				.names {
					font-size: 40rpx;
					color: #000000;
					font-weight: bold;
				}

				.service {
					font-size: 24rpx;
					color: #666666;
				}

				.device {
					font-size: 26rpx;
					color: #666666;
				}
			}

			.dbm {
				color: #1cbbb4;
			}
		}
	}
</style>